package cn.zglbk.generator.utils;
import cn.zglbk.generator.model.FileContentEntity;
import cn.zglbk.generator.model.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成
 * @author zglbk.cn
 * @email 1030681978@qq.com
 * @date 2020/10/21 15:16
 */
public class GenUtils {
   public static void buider(){
        List<FileContentEntity> entity = ReadFileUtils.readFileByPath();
        List<TableEntity> tableEntity = EntityUtils.wrappingTableEntity(entity);
        generatorCode(tableEntity);
    }
    private static void generatorCode(List<TableEntity> entity){
        //配置信息
        Configuration config = getConfig();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //添加到zip
        for (TableEntity tableEntity : entity) {

            generatorCode(tableEntity,zip,config);
        }
        byte[] bytes =outputStream.toByteArray();
        try {
            FileUtils. writeByteArrayToFile ( new  File ( config.getString("writePath") + "codes.zip" ),bytes ) ;
        } catch (IOException e) {
            throw new FsyException("文件写入路劲异常：" + config.getString("writePath"), e);
        }
        IOUtils.closeQuietly(zip);
    }
    private static void generatorCode(TableEntity entity,ZipOutputStream zip,Configuration config){

        //设置velocity资源加载器x`
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        entity.setClassName(StringUtils.tableToJava(entity.getClassName(),config.getStringArray("tablePrefix")));
        VelocityContext context = new VelocityContext(wrappingMap(config,entity));
        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            System.out.println(sw.toString());
            try {
                zip.putNextEntry(new ZipEntry(getFileName(template, entity.getClassName(), config.getString("package"), config.getString("moduleName"))));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new FsyException("渲染模板失败，表名：" + entity.getTableName(), e);
            }
        }
    }
    /**
     * 获取文件名
     */
    private static String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (org.apache.commons.lang.StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }

        if (template.contains("JavaBroadcastBean.java.vm")) {
            return packagePath + "bean" + File.separator + className + "Bean.cs";
        }
        return null;
    }

    private static Map<String, Object> wrappingMap(Configuration config,TableEntity entity){
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", entity.getTableName());
        map.put("comments", entity.getComments());
        map.put("className", entity.getClassName());
        map.put("columns", entity.getColumns());
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        return map;
    }
    private static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>(1);
        templates.add("template/JavaBroadcastBean.java.vm");
        return templates;
    }
    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new FsyException("获取配置文件失败，", e);
        }
    }
}
